package com.zigong.app.ui.adapter.holder;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.adapter.holder.BaseRecylerHolder;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.TextViewExpandableAnimation;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zigong.app.R;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.ADynamicsItem;
import com.zigong.app.beans.ContentImage;
import com.zigong.app.beans.FComment;
import com.zigong.app.beans.ImageUr;
import com.zigong.app.ui.activities.CommentDetailActivity;
import com.zigong.app.ui.adapter.PicAdapter;
import com.zigong.app.ui.utils.GlideCircleTransform;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.ItemImagTarget;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zigong.app.base.BaseActivity.EX_COMMENT_TYPE;
import static com.zigong.app.base.BaseActivity.EX_DATA;

/**
 * Created by Administrator on 2017/9/3 0003.
 */

public class AnchorCircleHolder extends BaseRecylerHolder<ADynamicsItem> {
    @BindView(R.id.item_anchor_home_dynamics_img)
    protected ImageView img;
    @BindView(R.id.item_anchor_dynamics_home_name)
    protected CustomFontTextView name;
    @BindView(R.id.item_anchor_dynamics_home_time)
    protected CustomFontTextView time;
    //    @BindView(R.id.item_anchor_dynamics_home_lable)
//    protected CustomFontTextView lable;
    @BindView(R.id.item_anchor_dynamics_home_page_intro)
    protected TextViewExpandableAnimation intro;
    @BindView(R.id.item_anchor_dynamic_home_pic)
    protected RecyclerView pic_list;
    @BindView(R.id.item_anchor_home_dynamics_video_rl)
    protected ViewGroup video_rl;
    @BindView(R.id.item_anchor_home_dynamics_video_coverImg)
    protected ImageView coverImage;
    @BindView(R.id.item_anchor_home_dynamic_divider)
    protected View divider;
    @BindView(R.id.item_anchor_home_dynamics_video_play)
    protected ImageView play;
    @BindView(R.id.item_achor_single_temp)
    protected View singleTemp;
    @BindView(R.id.item_anchor_dynamics_home_page_ll_four)
    protected ViewGroup four_ll;
    @BindView(R.id.item_anchor_dynamics_home_page_img1)
    protected CustomEXImageView img1;
    @BindView(R.id.item_anchor_dynamics_home_page_img2)
    protected CustomEXImageView img2;
    @BindView(R.id.item_anchor_dynamics_home_page_img3)
    protected CustomEXImageView img3;
    @BindView(R.id.item_anchor_dynamics_home_page_img4)
    protected CustomEXImageView img4;
    @BindView(R.id.item_anchor_dynamics_home_page_img5)
    protected CustomEXImageView img5;
    @BindView(R.id.item_anchor_dynamics_home_page_img6)
    protected CustomEXImageView img6;
    @BindView(R.id.item_anchor_dynamics_home_page_rl)
    protected ViewGroup rl_type;
    @BindView(R.id.item_anchor_home_delete)
    protected View deleteBtn;

    @BindView(R.id.layout_title)
    protected View headView;
    @BindView(R.id.iv_item_anchor_title)
    protected ImageView ivHeadView;
    @BindView(R.id.tv_item_anchor_title_name)
    protected CustomFontTextView tvHeadText;

    @BindView(R.id.tv_anchor_dynamics_home_page_more)
    protected CustomFontTextView tvMore;
    @BindView(R.id.tv_anchor_up)
    protected CustomFontTextView tvUp;
    @BindView(R.id.tv_anchor_comment)
    protected CustomFontTextView tvComment;


    @BindView(R.id.v_bottom_line)
    protected View vBottomLine;
    @BindView(R.id.item_anchor_dynamics_home_page_comment)
    protected LinearLayout llComment;

    private GridLayoutManager manager;
    private PicAdapter picAdapter;
    private String homePageUrl, title;

    private ItemImagTarget coverTarget;

    private ADynamicsItem dyTemp;
    private ArrayList<ContentImage> contentImage;

    public AnchorCircleHolder(final Context context, View itemView) {
        super(context, itemView);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CommentDetailActivity.class);
                intent.putExtra(EX_DATA, dyTemp);
                intent.putExtra(EX_COMMENT_TYPE, 3);
                context.startActivity(intent);
            }
        });
        intro.setOnStateChangeSetting(new TextViewExpandableAnimation.OnStateChangeSetting() {
            @Override
            public void reInitStateView(TextView stateView) {
                stateView.setText(R.string.newes_see_all);
            }

            @Override
            public void onStateChanged(TextView stateView, boolean isShrink) {
                JLog.e(" is shrink=" + isShrink + "   " + this);
                intro.getStateImg().setRotation(isShrink ? 90 : -90);
            }
        });
        coverTarget = new ItemImagTarget(coverImage);
        singleTemp.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (singleTemp.getWidth() > 0) {
                    coverTarget.setMxW(singleTemp.getWidth());
                    singleTemp.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
        intro.setOnStateChangeListener(new TextViewExpandableAnimation.OnStateChangeListener() {
            @Override
            public void onStateChange(boolean isShrink) {
                if (dyTemp != null) {
                    dyTemp.setShrink(isShrink);
                }
            }
        });

    }

    @Override
    protected void initInject() {
        ButterKnife.bind(this, itemView);
    }

    @Override
    public void setData(ADynamicsItem aDynamicsItem) {
        dyTemp = aDynamicsItem;
        name.setText(aDynamicsItem.getAnchorName());
        time.setText(DateUtils.formatDate(DateUtils.getDataDate(aDynamicsItem), "MM-dd HH:mm"));
        intro.setText(aDynamicsItem.getContentText());
        title = aDynamicsItem.getAnchorName();
        homePageUrl = aDynamicsItem.getAnchorInfoUrl();

        if (aDynamicsItem.getContentComment() != null && ListUtils.isListValued(aDynamicsItem.getContentComment().getCommentList())) {
            int count = aDynamicsItem.getContentComment().getCommentCount();
            if (count > 0) {
                tvComment.setText(String.valueOf(count));
            } else {
                tvComment.setText("");
            }

            llComment.setVisibility(View.VISIBLE);
            llComment.removeAllViews();
            ArrayList<FComment> fComments = aDynamicsItem.getContentComment().getCommentList();
            LayoutInflater inflater = LayoutInflater.from(context);
            if (fComments.size() == 1) {
                CustomFontTextView view = (CustomFontTextView) inflater.inflate(R.layout.item_author_comment, null);
                FComment fComment = fComments.get(0);
                String txt = "";
                if (!TextUtils.isEmpty(fComment.getAnswerTo())) {
                    view.setText(fComment.getCommentSpanned());
                } else {
                    txt = fComment.getNickName() + " : " + fComment.getComment();
                    view.setText(txt);
                }

                llComment.addView(view);
            } else if (fComments.size() >= 2) {
                for (int i = 0; i < 2; i++) {
                    CustomFontTextView view = (CustomFontTextView) inflater.inflate(R.layout.item_author_comment, null);
                    FComment fComment = fComments.get(i);
                    String txt = "";
                    if (!TextUtils.isEmpty(fComment.getAnswerTo())) {
                        view.setText(fComment.getCommentSpanned());
                    } else {
                        txt = fComment.getNickName() + " : " + fComment.getComment();
                        view.setText(txt);
                    }
                    llComment.addView(view);
                }
            }
        } else {
            tvComment.setText("");
            llComment.setVisibility(View.GONE);
        }
        if (!aDynamicsItem.getAttitudesStatus()) {
            Drawable drawable = context.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvUp.setDrawables(drawable, null, null, null);
            tvUp.setTextColor(context.getResources().getColor(R.color.colorOpinionSelectNo));
        } else {
            Drawable drawable = context.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvUp.setDrawables(drawable, null, null, null);
            tvUp.setTextColor(context.getResources().getColor(R.color.color_doup));
        }
        int upCount = aDynamicsItem.getAttitudesCount();
        if (upCount > 0) {
            tvUp.setText(String.valueOf(upCount));
        } else {
            tvUp.setText("");
        }
        tvUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, v, getAdapterPosition());
                }
            }
        });
        tvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, v, getAdapterPosition());
                }
            }
        });


//        if(!TextUtils.isEmpty(aDynamicsItem.getAnchorAvatar())){
        GlideUtil.getGlid(context, aDynamicsItem.getAnchorAvatar()).error(R.mipmap.icon_circle_avatar)
                .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(context))
                .into(img);
//        }
        int pa = context.getResources().getDimensionPixelOffset(R.dimen.item_list_large_margin_top);
        intro.resetState(aDynamicsItem.isShrink());
        if (TextUtils.isEmpty(aDynamicsItem.getContentVideo()) && !ListUtils.isListValued(aDynamicsItem.getContentImage())) {
            rl_type.setVisibility(View.GONE);
            intro.setPadding(pa, 0, pa, pa);
        } else {
            rl_type.setVisibility(View.VISIBLE);
            intro.setPadding(pa, 0, pa, 0);
        }
        intro.resetState(aDynamicsItem.isShrink());
        if (TextUtils.isEmpty(aDynamicsItem.getContentVideo())) {
            play.setVisibility(View.GONE);
            coverImage.setVisibility(View.GONE);
            contentImage = aDynamicsItem.getContentImage();
            if (ListUtils.isListValued(contentImage)) {
                if (contentImage.size() == 1) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.VISIBLE);
                    coverImage.setVisibility(View.VISIBLE);
                    four_ll.setVisibility(View.GONE);
//                    GlideUtil.getGlideWithLarge169Def(context, contentImage.get(0).getImageUrl()).into(coverImage);
                    GlideUtil.getGlideWith11DefNoFit(context, contentImage.get(0).getImageUrl()).into(coverTarget);
                } else if (contentImage.size() == 4) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.VISIBLE);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(0).getImageUrl(), img1);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(1).getImageUrl(), img2);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(2).getImageUrl(), img4);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(3).getImageUrl(), img5);
                    img3.setImageDrawable(null);
                    img6.setImageDrawable(null);
                } else {
                    initView(contentImage);
                    pic_list.setVisibility(View.VISIBLE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.GONE);
                }
            } else {
                pic_list.setVisibility(View.GONE);
                video_rl.setVisibility(View.GONE);
                four_ll.setVisibility(View.GONE);
            }
        } else {
            pic_list.setVisibility(View.GONE);
//            imgSingle.setVisibility(View.GONE);
            video_rl.setVisibility(View.VISIBLE);
            coverImage.setVisibility(View.VISIBLE);
            play.setVisibility(View.VISIBLE);
            four_ll.setVisibility(View.GONE);
            String coverImageUrl = aDynamicsItem.getCoverImage();
            GlideUtil.getGlideWith11DefNoFit(context, coverImageUrl).into(coverTarget);
        }
    }

    private void initView(ArrayList<ContentImage> dataImgs) {
        //if (dataImgs.size() == 4) {
        //  manager = new GridLayoutManager(context, 2);
        // } else {
        ArrayList<ImageUr> imageUrs = new ArrayList<>();
        for (ContentImage contentImage : dataImgs) {
            ImageUr imageUr = new ImageUr();
            imageUr.setImageUrl(contentImage.getImageUrl());
            imageUrs.add(imageUr);
        }
        manager = new GridLayoutManager(context, 3);
        //  }
        pic_list.setItemAnimator(new DefaultItemAnimator());
        pic_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        if (picAdapter == null) {
            // new UiListMarginUtils().setMargin(context, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
            picAdapter = new PicAdapter(context, imageUrs);
        } else {
            picAdapter.setData(imageUrs);
        }
        pic_list.setAdapter(picAdapter);
    }

    @OnClick(value = {R.id.item_anchor_home_dynamics_video_play})
    public void playClick(View view) {
        if (internalClick != null) {
            internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
        }
    }

    @OnClick(R.id.item_anchor_home_delete)
    public void delectClick(View view) {
        if (internalClick != null) {
            view.setTag(R.id.item_news_mode_tag, dyTemp);
            internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
        }
    }

    @OnClick({R.id.item_anchor_home_single, R.id.item_anchor_home_dynamics_video_coverImg})
    public void onlyImgClick(View view) {
        if (dyTemp == null || !TextUtils.isEmpty(dyTemp.getContentVideo()) || dyTemp.getContentImage() == null || dyTemp.getContentImage().size() == 0
                || dyTemp.getContentImage().get(0) == null || TextUtils.isEmpty(dyTemp.getContentImage().get(0).getImageUrl())) {
            return;
        }
        String path = UrlUtils.linkUrls(Constances.ST_BASE_URL, dyTemp.getContentImage().get(0).getImageUrl());
        String type = (path.endsWith(".gif") || path.endsWith(".GIF")) ? "image/gif" : "image";
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        intent.putExtra("type", 1);
        ArrayList<LocalMedia> list = new ArrayList<>();
        list.add(new LocalMedia(path, "", type));
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, list);
        intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
        context.startActivity(intent);
    }

    @OnClick(value = {R.id.item_anchor_dynamics_home_page_img1, R.id.item_anchor_dynamics_home_page_img2,
            R.id.item_anchor_dynamics_home_page_img4, R.id.item_anchor_dynamics_home_page_img5})
    public void imgClick(View view) {
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        switch (view.getId()) {
            case R.id.item_anchor_dynamics_home_page_img1:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
                break;
            case R.id.item_anchor_dynamics_home_page_img2:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 1);
                break;
            case R.id.item_anchor_dynamics_home_page_img4:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 2);
                break;
            case R.id.item_anchor_dynamics_home_page_img5:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 3);
                break;

        }
        List<LocalMedia> images = new ArrayList<LocalMedia>();
        for (ContentImage imageUr : contentImage) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(Constances.ST_BASE_URL + imageUr.getImageUrl());
            images.add(localMedia);
        }

        intent.putExtra("type", 1);
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) images);
        context.startActivity(intent);
    }


//    @OnClick(value = {R.id.item_anchor_home_dynamics_img,R.id.item_anchor_home_dynamics_img_ll})
//    public void homePageClick(View view) {
//        Intent intent = new Intent(context, AnchorHomePageActivity.class);
//        if (!TextUtils.isEmpty(homePageUrl) && homePageUrl.endsWith(".json")) {
//            intent.putExtra(BaseActivity.EX_URL, homePageUrl);
//            intent.putExtra(BaseActivity.EX_TITLE, title);
//            context.startActivity(intent);
//        } else {
//           // Toast.makeText(context, "错误url", Toast.LENGTH_SHORT).show();
//        }
//    }

    public CustomFontTextView getTvUp() {
        return tvUp;
    }

    @Override
    public AnchorCircleHolder setInternalClick(OnItemInternalClick internalClick) {
        super.setInternalClick(internalClick);
        return this;
    }

    public AnchorCircleHolder setLastItem(boolean isLast) {
        if (isLast) {
            divider.setVisibility(View.GONE);
        } else {
            divider.setVisibility(View.VISIBLE);
        }
        return this;
    }

    public void enableDelete() {
        if (deleteBtn != null) {
            deleteBtn.setVisibility(View.VISIBLE);
        }
    }
}
